package com.coolingme.springframework.webmvc.servlet;

import java.io.File;

/**
 * 视图解析器
 *
 * @author wangyue
 * @date 2024/9/4 11:46
 */
public class MeViewResolver {

    /**
     * 模板后缀
     */
    private final String DEFAULT_TEMPLATE_SUFFIX = ".html";

    /**
     * 模板的存放文件目录，D://XXX/layouts
     */
    private File templateRootDir;

    public MeViewResolver(String templateRoot) {
        String templateRootPath = this.getClass().getClassLoader().getResource(templateRoot).getFile();
        templateRootDir = new File(templateRootPath);
    }

    public MeView resolveViewName(String viewName) {
        if (null == viewName || "".equals(viewName.trim())) {
            return null;
        }
        // 是否带视图后缀
        viewName = viewName.endsWith(DEFAULT_TEMPLATE_SUFFIX) ? viewName : (viewName + DEFAULT_TEMPLATE_SUFFIX);
        // 根据名称找到视图文件，D://XXX/layouts/viewName.html
        File templateFile = new File((templateRootDir.getPath() + "/" + viewName)
                .replaceAll("/+", "/"));

        if (!templateFile.exists()) {
            return null;
        }

        return new MeView(templateFile);
    }
}
